<template>
	<view class="web">

		<!-- 聊天页面 -->
		<view class="chat_content">

			<view v-for="item in list" :key="item.id" class="content_right"
				:class="{left_right:item.userid!=user.userid}">

				<view class="right_text1">已读</view>
				<view class="right_text2">

					<text v-if="item.type=='text'">{{item.content}}</text>
					<image class="msg_img" v-if="item.type=='img'" :src="baseImgUrl+item.content" mode="widthFix">
					</image>
					<view @click="palyVoice(item.content)" v-if="item.type=='voice'" class="">
						语音图标
					</view>
					


				</view>
				<i class="iconfont icon-yousanjiao"></i>
				<image class="photo" src="/static/images/chat_r.png" mode=""></image>
			</view>

			<!-- 右边 -->
		</view>
		<!-- 聊天页面 -->
		<!-- 输入框 -->
		<view class="input_body">

			<view class="input_box">
				<view @click="isVoice=!isVoice" class="box_1">
					<i  class="iconfont icon-yuyin"></i>
				</view>
				<view @touchend="stopRecord" @touchstart="startRecord" v-if="isVoice" class="box_2">
					 按住 说话
				</view>
				<view v-else class="box_2">
					<input @focus="isUpload=false" v-model="msgData.content" type="text" />
				</view>
				<view  @click="send" v-if="msgData.content" class="sendbtn">
					发送
				</view>
				<view v-else class="right">
					<view  class="box_3">
						<i class="iconfont icon-xiaolian"></i>
					</view>
					<view @click="isUpload=true" class="box_4">
						<i class="iconfont icon-tianjia"></i>
					</view>
				</view>

			</view>
			<view v-show="isUpload" class="uploadimg">
				 
				<view @click="sendImg('album')" class="item">
					<view class="">
						照片
					</view>
				</view>
				<view @click="sendImg('camera')" class="item">
					<view class="">
						拍照
					</view>
				</view>
				<view class="item">
					<view class="">
						语音
					</view>
				</view>
			</view>


		</view>
		<!-- 输入框 -->
	</view>
</template>

<script>
	import {
		IMAGE_URL
	} from '../../utils/config.js'
	import {
		chooseImage,
		uploadFile
	} from '../../utils/images.js'
	import {
		setTransitionHooks
	} from "vue";
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				isVoice:false,
				voicePath: '',
				baseImgUrl: IMAGE_URL,
				isUpload: false,
				user: {
					userid: ""
				},
				toUser: {
					userid: "",
					name: "",
					photo: ""
				},
				list: [],
				socketOpen: false,
				msgData: {
					userid: "",
					toUserid: "",
					content: "",
					type: "login"
				}
			}
		},
		onNavigationBarButtonTap(e) {

			if (e.index === 0) {
				console.log("点击...");
			}
		},
		onLoad({
			userid,
			name,
			photo
		}) {
			let that=this;
			//监听停止录音
			recorderManager.onStop(async (result)=>{
				
				console.log("松开手指，停止录音");
				console.log(result.tempFilePath);
				
				uni.showLoading({
					title:"正在发送..."
				})
			  const res=await uploadFile(result.tempFilePath).catch(()=>{});
			  if(res?.errCode){
				  console.log("上传成功",res);
				  
				  //
				  that.msgData.type="voice";
				  let msg = JSON.stringify({
				  	...that.msgData,
				  	content: res.data
				  })
				  that.setMessage(msg);
				  
			  }
			  uni.hideLoading();
			  
			  
			})

			// let self = this;
			// recorderManager.onStop(function(res) {
			// 	console.log('recorder stop' + JSON.stringify(res));
			// 	self.voicePath = res.tempFilePath;
			// });

			this.user.userid = uni.getStorageSync("userid");
			this.toUser = {
				userid,
				name,
				photo
			};

			uni.setNavigationBarTitle({
				title: this.toUser.name
			})


			this.msgData.toUserid = userid;
 
			this.msgData.userid = uni.getStorageSync("userid")
			//创建连接
			uni.connectSocket({
				url: 'ws://123.57.237.81:600'
			});
			//监听连接是否成功
			uni.onSocketOpen(function(res) {
				that.socketOpen = true;
				console.log("连接成功");

				//连接成功  用户登录
				let msg = JSON.stringify(that.msgData);
				that.setMessage(msg);

			});
			uni.onSocketMessage(function(res) {
				let data = JSON.parse(res.data);
				if (data.type != "login") {

					that.list.push(data);
				}

				console.log('收到服务器内容：' + res.data);
			});


		},
		methods: {
			
			//播放语音
			palyVoice(url){
				innerAudioContext.src=this.baseImgUrl+url;
				innerAudioContext.play();
			},
			//开始录音
			 startRecord(){
				 console.log("开始录音");
				 recorderManager.start();
			 },
			 stopRecord(){
				 	 console.log("停止录音");
					 recorderManager.stop();
			 },
			async sendImg(type) {

				const res = await chooseImage(1, ['original', 'compressed'], [type]);

				if (res) {
					const fileRes = await uploadFile(res[0]);
					//上传成功图片 发送给对方
					if (fileRes.errCode === 10000) {


						this.msgData.type = "img";
						let msg = JSON.stringify({
							...this.msgData,
							content: fileRes.data
						})
						this.setMessage(msg);
						this.isUpload = false;

					}
				}

			},
			send() {
				this.msgData.type = "text";
				let msg = JSON.stringify(this.msgData)
				this.setMessage(msg);
			},
			setMessage(msg) {

				//客户端给服务端发送消息
				uni.sendSocketMessage({
					data: msg
				})
				this.msgData.content = "";

			}


		}
	}
</script>

<style>
	@import url('../../static/css/chat.css');
</style>